package com.shekhar.shortnotes.web;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.bson.types.ObjectId;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

import com.shekhar.shortnotes.domain.Note;
import com.shekhar.shortnotes.service.NoteService;
import com.shekhar.shortnotes.service.NotebookService;

@RequestMapping("/notebooks")
@Controller
public class NoteController {
    
    @Autowired
    NoteService noteService;

    @Autowired
    NotebookService notebookService;

    @RequestMapping(value = "/{notebookId}/notes", method = RequestMethod.POST, produces = "text/html")
    public String create(@PathVariable("notebookId") ObjectId notebookId,@Valid Note note, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, note);
            return "notes/create";
        }
        uiModel.asMap().clear();
        note.setId(UUID.randomUUID().toString());
//        notebook.getNotes().add(note);
//        noteService.saveNote(note);
        notebookService.pushNotesToNotebook(notebookId, note);
        return "redirect:/notebooks/"+encodeUrlPathSegment(notebookId.toString(), httpServletRequest)+"/notes/" + encodeUrlPathSegment(note.getId().toString(), httpServletRequest);
    }

    @RequestMapping(value = "/{notebookId}/notes", params = "form", produces = "text/html")
    public String createForm(@PathVariable("notebookId") ObjectId notebookId,Model uiModel) {
        populateEditForm(uiModel, new Note());
        uiModel.addAttribute("notebookId", notebookId.toString());
        return "notes/create";
    }

    @RequestMapping(value = "/{notebookId}/notes/{id}", produces = "text/html")
    public String show(@PathVariable("notebookId") ObjectId notebookId,@PathVariable("id") String id, Model uiModel) {
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("note", noteService.findNote(notebookId,id));
        uiModel.addAttribute("itemId", id);
        return "notes/show";
    }

    @RequestMapping(value = "/{notebookId}/notes", produces = "text/html")
    public String list(@PathVariable("notebookId") ObjectId notebookId,@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size,
            Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("notes", noteService.findNoteEntries(firstResult, sizeNo));
            float nrOfPages = (float) noteService.countAllNotes() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("notes", noteService.findAllNotes());
        }
        addDateTimeFormatPatterns(uiModel);
        return "notes/list";
    }

    @RequestMapping(value = "/{notebookId}/notes", method = RequestMethod.PUT, produces = "text/html")
    public String update(@PathVariable("notebookId") ObjectId notebookId,@Valid Note note, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, note);
            return "notes/update";
        }
        uiModel.asMap().clear();
        noteService.updateNote(note);
        return "redirect:/notes/" + encodeUrlPathSegment(note.getId().toString(), httpServletRequest);
    }

    @RequestMapping(value = "/{notebookId}/notes/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("notebookId") ObjectId notebookId,@PathVariable("id") String id, Model uiModel) {
        populateEditForm(uiModel, noteService.findNote(notebookId, id));
        return "notes/update";
    }

    @RequestMapping(value = "/{notebookId}/notes/{id}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("notebookId") ObjectId notebookId,@PathVariable("id") String id, @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        Note note = noteService.findNote(notebookId, id);
        noteService.deleteNote(note);
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/notes";
    }

    void addDateTimeFormatPatterns(Model uiModel) {
        uiModel.addAttribute("note_created_date_format", DateTimeFormat.patternForStyle("M-", LocaleContextHolder.getLocale()));
    }

    void populateEditForm(Model uiModel, Note note) {
        uiModel.addAttribute("note", note);
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("notebooks", notebookService.findAllNotebooks());
    }

    String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {
        }
        return pathSegment;
    }
}
